<template>
  <div class="new-va-container">

    <div class="form-container">
      <form @submit.prevent="submitForm">
        <div class="form-group">
          <label for="title">活动标题:</label>
          <input 
            id="title" 
            v-model="formData.title" 
            type="text" 
            required 
            placeholder="请输入活动标题"
          />
        </div>
        
        <div class="form-group">
          <label for="description">活动描述:</label>
          <textarea 
            id="description" 
            v-model="formData.description" 
            placeholder="请输入活动描述"
          ></textarea>
        </div>

        <div class="form-group">
          <label for="location">活动地点:</label>
          <input 
            id="location" 
            v-model="formData.location" 
            type="text" 
            required 
            placeholder="请输入活动地点"
          />
        </div>
        
        <div class="form-row three-columns">
          <div class="form-group">
            <label for="startTime">开始时间:</label>
            <input 
              id="startTime" 
              v-model="formData.startTime" 
              type="datetime-local" 
              required 
            />
          </div>
          
          <div class="form-group">
            <label for="endTime">结束时间:</label>
            <input 
              id="endTime" 
              v-model="formData.endTime" 
              type="datetime-local" 
              required 
            />
          </div>
          
          <div class="form-group">
            <label for="publishTime">发布时间:</label>
            <input 
              id="publishTime" 
              v-model="formData.publishTime" 
              type="datetime-local" 
              required 
            />
          </div>
        </div>
        
        <div class="form-row">
          <div class="form-group">
            <label for="recruitNum">招募人数:</label>
            <input 
              id="recruitNum" 
              v-model.number="formData.recruitNum" 
              type="number" 
              min="1"
              required 
              placeholder="请输入招募人数"
            />
          </div>
          
          <div class="form-group">
            <label for="status">状态:</label>
            <select id="status" v-model.number="formData.status" required>
              <option value="0">未开始</option>
              <option value="1">招募中</option>
              <option value="2">进行中</option>
              <option value="3">已结束</option>
            </select>
          </div>
        </div>
        
        <div class="form-group">
          <label for="remark">备注:</label>
          <textarea 
            id="remark" 
            v-model="formData.remark" 
            placeholder="请输入备注信息"
          ></textarea>
        </div>
        
        <div class="form-actions">
          <button type="button" class="cancel-button" @click="cancel">返回列表</button>
          <button type="submit" class="submit-button">{{ isEditMode ? '更新活动' : '创建活动' }}</button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'

// 定义表单数据结构
interface FormData {
  activityId?: number
  title: string
  description: string
  startTime: string
  endTime: string
  location: string
  recruitNum: number
  status: number
  publishTime: string
  remark: string
}

// 定义 props
const props = defineProps<{
  editData?: FormData
}>()

// 定义 emit 事件
const emit = defineEmits(['cancel', 'activity-created'])

// 表单数据
const formData = ref<FormData>({
  title: '',
  description: '',
  startTime: '',
  endTime: '',
  location: '',
  recruitNum: 1,
  status: 1,
  publishTime: '',
  remark: ''
})

// 判断是否为编辑模式
const isEditMode = ref(false)

// 初始化编辑模式
const initEdit = (activity: any) => {
  isEditMode.value = true
  formData.value = {
    activityId: activity.activityId,
    title: activity.title,
    description: activity.description,
    startTime: activity.startTime.slice(0, 16), // 格式化时间
    endTime: activity.endTime.slice(0, 16),
    location: activity.location,
    recruitNum: activity.recruitNum,
    status: activity.status,
    publishTime: activity.publishTime.slice(0, 16),
    remark: activity.remark
  }
}

// 定义 expose 方法
defineExpose({
  initEdit
})

// 取消操作
const cancel = () => {
  emit('cancel')
}

// 提交表单
const submitForm = async () => {
  try {
    const token = localStorage.getItem('token')
    
    if (isEditMode.value) {
      // 编辑模式 - 更新活动
      const response = await fetch('http://localhost:8080/va/update', {
        method: 'PUT',
        headers: {
          'token': token || '',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(formData.value)
      })
      
      const result = await response.json()
      
      if (result.success) {
        alert('志愿者活动更新成功')
        emit('activity-created')
      } else {
        throw new Error(result.message || '更新失败')
      }
    } else {
      // 创建模式 - 创建新活动
      const response = await fetch('http://localhost:8080/va/create', {
        method: 'POST',
        headers: {
          'token': token || '',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(formData.value)
      })
      
      const result = await response.json()
      
      if (result.success) {
        alert('志愿者活动创建成功')
        emit('activity-created')
      } else {
        throw new Error(result.message || '创建失败')
      }
    }
  } catch (err) {
    console.error('操作志愿者活动失败:', err)
    alert('操作志愿者活动失败: ' + (err instanceof Error ? err.message : '未知错误'))
  }
}

// 组件挂载时设置默认时间
onMounted(() => {
  const now = new Date()
  const publishTime = new Date(now.getTime() + 1000 * 60 * 60 * 24) // 默认发布时间为明天
  const startTime = new Date(now.getTime() + 1000 * 60 * 60 * 24 * 2) // 默认开始时间为后天
  const endTime = new Date(now.getTime() + 1000 * 60 * 60 * 24 * 2 + 1000 * 60 * 60 * 3) // 默认结束时间为开始时间后3小时
  
  // 只有在非编辑模式下才设置默认时间
  if (!isEditMode.value) {
    formData.value.publishTime = publishTime.toISOString().slice(0, 16)
    formData.value.startTime = startTime.toISOString().slice(0, 16)
    formData.value.endTime = endTime.toISOString().slice(0, 16)
  }
})
</script>

<style scoped>
.new-va-container {
  padding: 20px;
  background: none;
  border: none;
  box-shadow: none;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: none;
  border: none;
  box-shadow: none;
  padding: 0;
}

.header h2 {
  color: #333;
  margin: 0;
}

.cancel-button {
  background: linear-gradient(to right, #95a5a6, #7f8c8d);
  color: white;
  border: none;
  border-radius: 8px;
  padding: 12px 30px;
  font-size: 16px;
  cursor: pointer;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.cancel-button:hover {
  background: linear-gradient(to right, #7f8c8d, #6c7a7b);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
  transform: translateY(-1px);
}

.form-container {
  background: white;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.form-group {
  margin-bottom: 25px;
}

.form-row {
  display: flex;
  gap: 30px;
  margin-bottom: 35px;
}

.form-row.three-columns {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  margin-bottom: 25px;
}

.form-row .form-group {
  flex: 1;
  margin-bottom: 0;
}

label {
  display: block;
  margin-bottom: 8px;
  font-weight: bold;
  color: #333;
}

input, select, textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid #bbb;
  border-radius: 4px;
  font-size: 16px;
  box-sizing: border-box;
  background-color: #fff;
  color: #333;
}

input:focus, select:focus, textarea:focus {
  outline: none;
  border-color: #4CAF50;
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.2);
}

input::placeholder, textarea::placeholder {
  color: #666;
}

textarea {
  min-height: 100px;
  resize: vertical;
}

.form-actions {
  margin-top: 40px;
  text-align: center;
}

.form-actions button {
  margin: 0 10px;
}

.submit-button {
  background: linear-gradient(to right, #66BB6A, #43A047);
  color: white;
  border: none;
  border-radius: 8px;
  padding: 12px 30px;
  font-size: 16px;
  cursor: pointer;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.submit-button:hover {
  background: linear-gradient(to right, #5BAE5F, #3D8F3F);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
  transform: translateY(-1px);
}

@media (max-width: 768px) {
  .form-row {
    flex-direction: column;
    gap: 25px;
    margin-bottom: 25px;
  }
  
  .form-row.three-columns {
    grid-template-columns: 1fr;
    gap: 25px;
    margin-bottom: 25px;
  }
  
  .form-group {
    margin-bottom: 20px;
  }
  
  .form-actions button {
    display: block;
    width: 100%;
    margin: 10px 0;
  }
}
</style>